using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Rapier.Kodachi.Engine;
using Rapier.Kodachi.Shared;
using System.Windows;
//using System.Windows.Input;
using Microsoft.Win32;

namespace Rapier.Kodachi
{
    public partial class Options : Form
    {

        #region Properties
        private bool _RestartNeeded = false;
        public bool RestartNeeded
        {
            get { return _RestartNeeded; }
            set { _RestartNeeded = value; }
        }
        #endregion

        #region Data Members
        private Controller controller;
        private Plugin activePlugin;
        #endregion

        #region Constructor
        public Options(Controller controller)
        {
            InitializeComponent();

            this.controller = controller;
            gridPlugins.Rows.Clear();

            int index = 0;
            foreach (Plugin plugin in controller.Plugins)
            {
                AddPluginToList(index, plugin);
                index++;
            }

            gridPlugins.DoubleClick += new EventHandler(gridPlugins_DoubleClick);
            gridPlugins.SelectionChanged += new EventHandler(gridPlugins_SelectionChanged);
            gridPlugins.CellContentClick += new DataGridViewCellEventHandler(gridPlugins_CellContentClick);
            gridPlugins.KeyDown += new System.Windows.Forms.KeyEventHandler(gridPlugins_KeyDown);

            btnClose.Click += new EventHandler(btnClose_Click);
            numberTextBoxSec.KeyDown += new System.Windows.Forms.KeyEventHandler(numberTextBox_KeyDown);
            linkUrl.LinkClicked += new LinkLabelLinkClickedEventHandler(linkUrl_LinkClicked);
        }
        #endregion

        #region Private Methods
        private void SetDataBindings()
        {
            this.numberTextBoxSec.DataBindings.Add("Enabled", cbClearQuery, "Checked");
            this.lblFreqQ.DataBindings.Add("Enabled", cbClearQuery, "Checked");
            this.lblSec.DataBindings.Add("Enabled", cbClearQuery, "Checked");
            this.comboUser.DataBindings.Add("Enabled", cbStartWithWindows, "Checked");

            this.cbClearQuery.DataBindings.Add("Checked", controller.Settings, "ClearQuery");
            this.cbHideOnHotKey.DataBindings.Add("Checked", controller.Settings, "HotKeyHides");
            this.cbStartWithWindows.DataBindings.Add("Checked", controller.Settings, "AutoStart");
            this.numberTextBoxSec.DataBindings.Add("Text", controller.Settings, "ClearQueryDuration");
            this.comboKeys.DataBindings.Add("SelectedItem", controller.Settings, "HotKey");
            this.comboUser.DataBindings.Add("Text", controller.Settings, "StartWithUser");
            this.cbUSBMode.DataBindings.Add("Checked", controller.Settings, "PortableMode");

        }

        private void AddPluginToList(int index, Plugin plugin)
        {
            if (plugin.HasSettings)
                gridPlugins.Rows.Add(new object[] { plugin.Enabled, plugin.Name, "Settings...", index });
            else
                gridPlugins.Rows.Add(new object[] { plugin.Enabled, plugin.Name, String.Empty, index });
        }

        //private void cb_Checked(object sender, RoutedEventArgs e)
        //{
        //   Plugin plugin = (sender as CheckBox).Tag as Plugin;
        //   plugin.Enabled = true;
        //   _RestartNeeded = true;
        //}

        //private void cb_Unchecked(object sender, RoutedEventArgs e)
        //{
        //   Plugin plugin = (sender as CheckBox).Tag as Plugin;
        //   plugin.Enabled = false;
        //   _RestartNeeded = true;
        //}

        void gridPlugins_DoubleClick(object sender, EventArgs e)
        {
            if (activePlugin.HasSettings)
                _RestartNeeded = activePlugin.ShowSettings();
        }

        private void ShowPluginInformation(Plugin plugin)
        {
            textName.Text = plugin.Name;
            textDescription.Text = plugin.Description;
            textVersion.Text = plugin.Version;
            textAuthor.Text = plugin.Author;
            linkUrl.Links.Clear();
            linkUrl.Text = plugin.Url;
            linkUrl.Links.Add(0, linkUrl.Text.Length, plugin.Url);
            textCopyright.Text = plugin.Copyright;

            //textSettings.Visibility = plugin.HasSettings ? Visibility.Visible : Visibility.Hidden;
        }

        private void LoadUserCombo()
        {
            comboUser.Items.Add("All Users");
            comboUser.Items.Add("Current User");
        }

        private void LoadKeyCombo()
        {
            foreach (System.Windows.Forms.Keys key in Enum.GetValues(typeof(System.Windows.Forms.Keys)))
            {
                if (key < System.Windows.Forms.Keys.Space)
                    continue;

                if (key > System.Windows.Forms.Keys.Space && key < System.Windows.Forms.Keys.D0)
                    continue;

                if (key > System.Windows.Forms.Keys.Z && key < System.Windows.Forms.Keys.NumPad0)
                    continue;

                if (key > System.Windows.Forms.Keys.NumPad9 && key < System.Windows.Forms.Keys.F1)
                    continue;

                if (key > System.Windows.Forms.Keys.F12)
                    continue;

                comboKeys.Items.Add(key);
            }
        }

        private void LoadKeyModifiers()
        {
            if ((controller.Settings.HotKeyModifiers | (int)HotKey.HotKeyModifiers.Alt) == controller.Settings.HotKeyModifiers)
                cbAlt.Checked = true;

            if ((controller.Settings.HotKeyModifiers | (int)HotKey.HotKeyModifiers.Control) == controller.Settings.HotKeyModifiers)
                cbControl.Checked = true;

            if ((controller.Settings.HotKeyModifiers | (int)HotKey.HotKeyModifiers.Shift) == controller.Settings.HotKeyModifiers)
                cbShift.Checked = true;

            if ((controller.Settings.HotKeyModifiers | (int)HotKey.HotKeyModifiers.Windows) == controller.Settings.HotKeyModifiers)
                cbWin.Checked = true;
        }

        private void SaveKeyModifiers()
        {
            int modifiers = 0;

            if (cbAlt.Checked)
                modifiers |= (int)HotKey.HotKeyModifiers.Alt;

            if (cbControl.Checked)
                modifiers |= (int)HotKey.HotKeyModifiers.Control;

            if (cbShift.Checked)
                modifiers |= (int)HotKey.HotKeyModifiers.Shift;

            if (cbWin.Checked)
                modifiers |= (int)HotKey.HotKeyModifiers.Windows;

            controller.Settings.HotKeyModifiers = modifiers;
        }

        private void CopyPluginsForPortableMode()
        {
            if (cbUSBMode.Checked)
            {
                MessageBox.Show("Copy Stuff...");
            }
        }

        private void UpdateRegistryForAutoStart()
        {
            try
            {
                if (cbStartWithWindows.Checked)
                {
                    RegistryKey addKey;
                    RegistryKey delKey;
                    if (comboUser.Text == "Current User")
                    {
                        addKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
                        delKey = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
                    }
                    else
                    {
                        addKey = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
                        delKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
                    }

                    //Set the program to start with Windows:
                    addKey.SetValue(System.Windows.Forms.Application.ProductName, System.Windows.Forms.Application.ExecutablePath);
                    delKey.DeleteValue(System.Windows.Forms.Application.ProductName, false);
                }
                else
                {
                    //Clear both keys
                    RegistryKey delKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
                    RegistryKey delKey2 = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
                    delKey.DeleteValue(System.Windows.Forms.Application.ProductName, false);
                    delKey2.DeleteValue(System.Windows.Forms.Application.ProductName, false);
                }
            }
            catch (Exception ex)
            {
                controller.Host.NotifyError("Failed to save autostart settings...", ex.Message);
            }
        }
        #endregion

        #region Event Handlers
        void gridPlugins_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (gridPlugins.SelectedRows.Count == 1)
                {
                    _RestartNeeded = activePlugin.ShowSettings();
                }

                e.Handled = true;
            }
        }

        void gridPlugins_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1)
                return;

            if (e.ColumnIndex == gridPlugins.Columns["settings"].Index)
            {
                _RestartNeeded = activePlugin.ShowSettings();
            }
            else if (e.ColumnIndex == gridPlugins.Columns["pluginActive"].Index)
            {
                int index = (int)gridPlugins.Rows[e.RowIndex].Cells["index"].Value;
                Plugin plugin = controller.Plugins[index];
                plugin.Enabled = (bool)(gridPlugins.Rows[e.RowIndex].Cells["pluginActive"].EditedFormattedValue);
                _RestartNeeded = true;
            }
        }

        void linkUrl_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(activePlugin.Url);
        }

        void gridPlugins_SelectionChanged(object sender, EventArgs e)
        {
            //if (e.AddedItems.Count == 0)
            //   return;

            if (gridPlugins.SelectedRows.Count == 1)
            {
                int index = (int)gridPlugins.SelectedRows[0].Cells["index"].Value;
                activePlugin = controller.Plugins[index];
                ShowPluginInformation(activePlugin);
            }
            //StackPanel stackPanel = (StackPanel)(e.AddedItems[0] as ListViewItem).Content;
            //int index = Convert.ToInt32((stackPanel.Children[2] as Label).Content.ToString());


        }

        void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            //this.DataContext = controller.Settings;
            LoadKeyCombo();
            LoadKeyModifiers();
            LoadUserCombo();
            SetDataBindings();
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);

            SaveKeyModifiers();
            UpdateRegistryForAutoStart();
            CopyPluginsForPortableMode();
        }

        private void numberTextBox_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (!(e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9) &&
               !(e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9))
            {
                e.Handled = true;
            }
        }
        #endregion
    }
}